package com.btcode.web.core.respone;

import com.btcode.common.AbstractSingleton;
import com.btcode.json.IJsonConver;
import com.btcode.json.JsonConver;
import com.btcode.web.core.unit.URLUtil;
import com.btcode.web.core.unit.WebContext;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

public class JsonRespone extends AbstractSingleton {

    public JsonRespone() {

    }

    protected void outputString(String msg) throws IOException {
        if (msg == null) {
            return;
        }
        WebContext.getResponse().getWriter().write(msg);
        WebContext.getResponse().getWriter().flush();
    }

    public void outputObj(Object obj, ResultFlag resultFlag, String resultFlagDesc)
        throws IOException {

        HashMap<String, Object> result = new HashMap<>();
        result.put("platform", URLUtil.getProjectName());
        result.put("result_flag", resultFlag.toString());
        result.put("result_flag_dsc", resultFlagDesc);

        if (obj == null) {
            obj = new ArrayList<>();
        }
        else if (!(obj instanceof Collection<?>)) {
            List<Object> objList = new ArrayList<>();
            objList.add(obj);
            obj = objList;
        }

        result.put("data", obj);

        String jsonResult = getJsonConver().toJson(result);

        outputString(jsonResult);
    }

    protected IJsonConver getJsonConver() {
        return AbstractSingleton.getInstance(JsonConver.class);
    }

}
